
package net.zio.kamenriderzioaddon.network;

import net.zio.kamenriderzioaddon.procedures.HenshinkeyProcedure;
import net.zio.kamenriderzioaddon.KamenRiderZioAddonMod;

import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.eventbus.api.SubscribeEvent;

import net.minecraft.world.level.Level;
import net.minecraft.world.entity.player.Player;
import net.minecraft.network.FriendlyByteBuf;

import java.util.Objects;
import java.util.function.Supplier;

/**
 * 这是一个用于处理玩家按键事件的消息类
 */
@Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD)
public class HenshinMessage {
	int type, pressedms;

	public HenshinMessage(int type, int pressedms) {
		this.type = type;
		this.pressedms = pressedms;
	}

	public HenshinMessage(FriendlyByteBuf buffer) {
		this.type = buffer.readInt();
		this.pressedms = buffer.readInt();
	}

	public static void buffer(HenshinMessage message, FriendlyByteBuf buffer) {
		buffer.writeInt(message.type);
		buffer.writeInt(message.pressedms);
	}

	public static void handler(HenshinMessage message, Supplier<NetworkEvent.Context> contextSupplier) {
		NetworkEvent.Context context = contextSupplier.get();
		context.enqueueWork(() -> {
			pressAction(Objects.requireNonNull(context.getSender()), message.type, message.pressedms);
		});
		context.setPacketHandled(true);
	}

	/**
	 * 处理玩家按键事件的方法
	 *
	 * @param entity    触发事件的玩家实体
	 * @param type      按键类型（0 表示按下，1 表示松开）
	 * @param pressedms 按键持续时间（毫秒）
	 */
	public static void pressAction(Player entity, int type, int pressedms) {
		Level world = entity.level;
		double x = entity.getX();
		double y = entity.getY();
		double z = entity.getZ();
		// security measure to prevent arbitrary chunk generation
		if (!world.hasChunkAt(entity.blockPosition()))
			return;
		if (type == 0) {
			HenshinkeyProcedure.execute(world, x, y, z, entity);
		}
	}

	@SubscribeEvent
	public static void registerMessage(FMLCommonSetupEvent event) {
		KamenRiderZioAddonMod.addNetworkMessage(HenshinMessage.class, HenshinMessage::buffer, HenshinMessage::new, HenshinMessage::handler);
	}
}
